<template>
  <div v-if="isShow" :id="echartId" ref="Echarts" :style="`min-height:${isInCard ? '130' : '240'}px`"></div>
  <el-scrollbar v-else><el-empty description="暂无数据" :image-size="100" /></el-scrollbar>
</template>
<script>
import { defineComponent, toRefs, reactive, onMounted, ref, watch,onActivated } from 'vue'
import * as echarts from 'echarts'
import { toThousands } from '@/utils/number-util'
var myChart = null
export default defineComponent({
  name: 'PieEchat',
  props: {
    echartData: Object,
    echartId: String,
    isInCard: Boolean,
    isHidelegend: Boolean,
    // 是否展示饼图上面的百分比
    isShowPer: {
      type: Boolean,
      required: false,
      default: true
    },
  },
  setup(props) {
    let isShow = ref(true)
    let seriesData = ref([])
    const state = reactive({
      option: {}
    })
    const renderEchartPie = () => {
      state.option = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            console.log(params)
            let templete = ''
            let dataIndex = params.dataIndex //当前点击的柱子序号
            let yData = props.echartData.data[dataIndex].data
            templete = params.data.name + '\n'
            for (let i = 0; i < yData.length; i++) {
              let item = yData[i];
              let nameString = (item.key) ? (item.key + `: ` + toThousands(item.value) + (item.unit ? item.unit : '')) : (item.key + `: -`)
              templete += nameString
              templete += (i != yData.length - 1) ? `\n` : ''
            }
            console.log(params)
            return templete
          },
          extraCssText: 'max-width:120px; white-space: pre-wrap;word-break: break-all;word-wrap: break-word;'
        },
        color: ['#7DCFF3', '#FF8736', '#FDE76D', '#EDC5AA', '#96B9BF', '#CECECE'],
        legend: {
          // data: props.echartData.xLable
          left: '20px',  // 或者使用像素值，例如 '50px'
          bottom: '0',
          itemHeight: 8,
          itemWidth: 15,
          show: props.isHidelegend ? false : true
        },
        label: {
          formatter: props.isShowPer ? '{c}  {per|{d}%}' : '{c}',
          rich: {
            per: {
              color: '#fff',
              backgroundColor: '#666666',
              padding: [3, 4],
              borderRadius: 4
            }
          }
        },
        grid: {
          //以div为中心 向右缩进30%
          left: "2%",
          right: "0%",
          top: "10%",
          bottom: "20%",
          containLabel: true
        },
        graphic: [ //为环形图中间添加文字
          {
            type: "text",
            left: "center",
            top: "46%",
            style: {
              text: props.echartData.totalValue + props.echartData.unit,
              textAlign: "center",
              fill: "#282B32",
              fontSize: props.isInCard ? 14 : 24,
              fontWeight: 500
            },
          },
        ],
        series: seriesData.value,
      }
    }
    const initeCharts = () => {
      myChart = echarts.init(document.getElementById(props.echartId))
      // 绘制图表
      myChart.setOption(state.option)
      window.addEventListener("resize", () => { myChart.resize() }, true)
    }
    const packageSeriesData = () => {
      seriesData.value = []
      if (props.echartData.data && props.echartData.data.length > 0) {
        let series = {
          name: '',
          type: 'pie',
          radius: ['50%', '65%'],
          data: [],
        }
        props.echartData.data.forEach(function (item) {
          let dataItem = {
            value: item.data[0].value,
            name: item.name,
            itemStyle: {
              color: item.color
            }
          }
          series.data.push(dataItem)
        })
        seriesData.value.push(series)
        renderEchartPie()
      }
    }
    onMounted(() => {
    })
    onActivated(() => {
      myChart.resize()
    })
    watch(
      () => props.echartData,
      (val, preVal) => {
        //val为修改后的值,preVal为修改前的值
        console.log("message", val, preVal)
        if (!val.data) {
          isShow.value = false
        } else {
          isShow.value = true
          packageSeriesData()
          setTimeout(() => {
            initeCharts()
          }, 600)
        }
      },
      {
        //如果加了这个参数，值为true的话，就消除了惰性，watch会在创建后立即执行一次
        //那么首次执行，val为默认值,preVal为undefined
        immediate: true,
        //这个参数代表监听对象时，可以监听深度嵌套的对象属性
        //比如message是一个对象的话，可以监听到message.a.b.c，也就是message下的所有属性
        deep: true,
      }
    )
    return {
      isShow, seriesData, ...toRefs(state)
    }
  },
})
</script>

<style lang="scss" scoped></style>
